/*
 * @Author: AskMeWhy
 * @Date: 2020-12-01 18:05:43
 * @Last Modified by: AskMeWhy
 * @Last Modified time: 2021-02-02 18:27:15
 */

import { Component, Mixins, Provide } from "vue-property-decorator";
import FormMixin from "@/mixins/form.mixin";
import PreviewList from "@/views/module-manage/src/components/preview-template/index.vue";
import { State } from "vuex-class";

interface ModelMeta {
    id: string;
    moduleId: string;
    flowId: string;
    // 表单标题
    name: string;
    // 表单描述
    desc: string;
    // 表单分类
    typeId: string;
    // 期望采集数量
    expectedNum: number;
    // 发送周期
    sendingCycle: number;
    // 任务时间
    taskTime: any[];
    taskTimePoint: string;
    times: number;
    week: any[];
    month: number;
    // 自定义表单内容
    items: any[];
    // 关联部门
    departmentValue: any[];
    // 选择流程值
    // flowValue: string;
    // 流程名称
    flowName: string;
    // 流程描述
    flowDesc: string;
    receiverId: string;
    richText: string;
    categoryId: "";
}

interface FormData {
    name: string;
    description: string;
    richText: string;
}

@Component({
    components: {
        PreviewList
    }
})
export default class FormNormMixin extends Mixins(FormMixin) {
    @State(state => state.authArea) authArea: any;
    // 当前用户所处层级菜单
    get userLevel() {
        return this.$getUserLevel(
            this.authArea ? this.authArea.orgCategoryId || "" : ""
        );
        // return this.$getUserLevel("6");
    }

    get _isOperation() {
        return ["ADMIN", "OPERATION_ADMIN", "OPERATION"].includes(
            this.userLevel.name
        );
    }

    get _isOperationPage() {
        return this.$route.name === "OperationModuleManageForm";
    }

    get _isRegionalAdminPage() {
        return this.$route.name === "RegionalAdminModuleManageForm";
    }

    get _isTownAdminPage() {
        return this.$route.name === "TownAdminModuleManageForm";
    }

    get _isTownPage() {
        return this.$route.name === "TownModuleManageForm";
    }

    get _isDetail() {
        return this.$route.query.isDetail === "1";
    }

    get isSend() {
        return this.$route.query.isSend === "send";
    }

    get _isCopy() {
        return this.$route.query.isCopy === "copy";
    }

    get _isDeclare() {
        return !!this.$route.query.declareTypeId;
    }

    get _formStatus() {
        return this.$route.query.formStatus === "1";
    }

    @Provide("dataForm")
    dataForm() {
        return {};
    }

    @Provide("checkShow")
    checkShow() {
        return true;
    }

    @Provide("addSelect")
    addSelect() {
        return true;
    }

    nowId = "";
    currentFormId: any = "";

    formType = "add";
    activeName = "formDescribe";
    jsonCustom: any = {};
    showPreviewDialog = false;
    previewType = "form";

    // 表单描述tab切换时
    childTab = "text";

    model: ModelMeta = {
        id: "",
        moduleId: "",
        flowId: "",
        // 表格标题
        name: "",
        // 表格描述
        desc: "",
        // 表单分类
        typeId: "",
        // 期望采集数量
        expectedNum: 0,
        // 发送周期
        sendingCycle: 1,
        // 任务时间
        taskTime: [],
        taskTimePoint: "",
        times: 2,
        week: [],
        month: 1,
        items: [],
        // 关联部门
        departmentValue: [],
        // 流程名称
        flowName: "",
        // 流程描述
        flowDesc: "",
        receiverId: "",
        categoryId: "",
        richText: ""
    };

    // FormData: FormData = {
    //     name: "",
    //     desc: "",
    //     richText: ""
    // };

    richTextActiveName = "text";
    // 表单介绍的预览
    wechatDialogVisible = false;

    mounted() {
        this.init();
    }

    async init() {
        const { id, type, moduleId }: any = this.$route.query;
        this.model.id = id || "";
        this.model.moduleId = moduleId || "";
        this.formType = this._isCopy ? "add" : this.model.id ? type === "query" ? type : "edit" : "add";
        if (this.initSearchData) {
            await this.initSearchData();
        }
        this.initData();
    }

    initSearchData() {
        // console.log("initSearchData");
    }

    async initData() {
        if ((this.formType === "add" || (this.formType === "add" && !this.model.moduleId)) && !this._isCopy) {
            return;
        }
        const response: any = await this.$server["moduleManage/form/query"]({
            params: {
                id: this._isCopy ? this.model.id : this.formType === "add" ? this.model.moduleId : this.model.id
            }
        });
        if (this.responseHasError(response)) {
            return;
        }

        const data = response.data.data || {};
        const getItem = (arr: any) => {
            arr.forEach((item: any) => {
                item.tempId = item.id;
                if (item.itemType === 2) {
                    if (item.valueKindId === "6" || item.valueKindId === "7") {
                        item.options = item.options.map((cur: any) => {
                            return {
                                ...cur,
                                tempId: cur.id
                            };
                        });
                    }
                } else {
                    getItem(item.items);
                }
            });
        };
        getItem(data.items);

        const model = {
            // 表格标题
            name: this._isCopy ? data.name + "-复制" || "" : data.name || "",
            // 表格描述
            desc: data.descriptionType === 1 ? data.description : "",
            richText: data.descriptionType === 2 ? data.description : "",
            // 自定义表单内容
            items: data.items,
            typeId: data.typeId || "",
            // 关联部门
            departmentValue: data.departments.length && data.departments[0] === null ? [] : (data.departments.map((item: any) => item.departmentId) || []),
            receiverId: this.$route.query.receiverId ? this.$route.query.receiverId.toString() : ""
        };

        this.model = {
            ...this.model,
            ...model
        };
        this.richTextActiveName = data.descriptionType === 2 ? "rich" : "text";
        this.$nextTick(() => {
            this.resetInterceptRouter();
        });
    }

    async submit(type: any, send?: any) {
        console.log(send, this.model);
        const {
            items,
            // 表单类型
            typeId,
            // 采集数量
            expectedNum,
            // 发送次数 1单次2循环
            sendingCycle,
            // 2每天3每周4每月
            times,
            week,
            month,
            taskTime,
            taskTimePoint,
            // 关联部门
            departmentValue
        } = this.model;
        const axiosInfo: any = {
            url: ""
        };
        const governmentId = this.authArea ? this.authArea.governmentId || 0 : 0;
        const departments: any[] = [];
        departmentValue.forEach((item: any) => {
            departments.push({
                departmentId: item,
                governmentId: governmentId
            });
        });
        const formCycle = this._isTownAdminPage
            ? {}
            : {
                  // 采集数量
                  collectNum: expectedNum,
                  // 循环类型 1 单次， 2 每天， 3 每周， 4 每月
                  cycle: sendingCycle === 1 ? sendingCycle : times,
                  // 循环时间 比如，周1，2，3；每月 1 日。以英文逗号隔开
                  cycleDate: sendingCycle === 2 ? times === 3 ? week : times === 4 ? month : "" : "",
                  endDateTime: taskTime[1],
                  startDateTime: sendingCycle === 1 ? taskTime[0] : "",
                  // 开始采集时间 当cycle为2，3，4 时用这个字段
                  startTime: sendingCycle === 2 ? taskTimePoint : ""
            };
        const params: any = {
            status: type === "DRAFT" ? 0 : ((this._isTownAdminPage || this._isTownPage) && this.activeName === "formDesign" && !this._isDeclare) ? 0 : 1,
            // 表格标题
            name: this.model.name,
            // 表格描述
            description: this.childTab === "text" ? this.model.desc : this.model.richText,
            // 自定义表单内容
            descriptionType: this.childTab === "text" ? 1 : 2,
            items: this.addSort(JSON.parse(JSON.stringify(items))),
            // 关联部门
            departments: departments.length ? departments : this._isRegionalAdminPage ? this.authArea ? [{ cityCode: this.authArea.cityCode }] : undefined : undefined,
            typeId: typeId,
            formKind: this._isOperationPage ? 1 : this._isRegionalAdminPage ? 4 : this._isTownAdminPage ? 2 : this._isTownPage ? 3 : 0,
            formCycle
        };
        if (this._isDeclare) {
            this.addDeclareForm(params);
            return false;
        }
        if (this.formType === "edit" || this.nowId) {
            params.id = this.model.id || this.nowId;
            axiosInfo.url = "moduleManage/form/update";
        } else if (this.formType === "add") {
            axiosInfo.url = "moduleManage/form/add";
        }
        const response = await this.$server[axiosInfo.url]({
            data: params
        });
        if (this.responseHasError(response)) {
            return;
        }
        this.$message({
            message: "操作成功",
            type: "success",
            duration: 1500
        });
        this.resetInterceptRouter(() => {
            if (this._isOperationPage || this._isRegionalAdminPage || (params.status === 0 && type !== "RELEASED")) {
                this.goBackList();
            } else {
                this.nowId = this.nowId || response.data.data;
                this.activeName = "contactProcess";
                if (axiosInfo.url === "moduleManage/form/add" && this._isCopy) {
                    this.model.id = response.data.data;
                    this.nowId = response.data.data;
                    this.$router.push({
                        name: this.$route.name || "",
                        query: { id: response.data.data }
                    });
                }
            }
        });
    }

    goBackList() {
        this.$router.push({
            name: this._isOperationPage ? "OperationModuleManageList" : this._isRegionalAdminPage ? "RegionalAdminModuleManageList" : this._isTownPage ? "TownModuleManageHome" : "TownAdminModuleManageList"
        });
    }

    // 添加sort索引
    addSort(list: any) {
        list.forEach((item: any, index: any) => {
            item.sort = index;
            item.id = undefined;
            item.unitKindId = item.unitKindId || undefined;
            item.unitKindName = item.unitKindName || undefined;
            item.valueKindId = item.valueKindId || undefined;
            item.valueKindName = undefined;
            item.valueKindValue = undefined;
            item.formId = undefined;
            item.childrenFormId = undefined;
            item.extData = undefined;
            item.itemValue = undefined;
            if (item.items && item.items.length) {
                item.items = this.addSort(item.items);
            }
        });
        return list;
    }

    // 添加上报配置表单
    async addDeclareForm(params: any) {
        const url = this.$route.query.id && !this._isCopy ? "declare/updateForm" : "declare/addForm";
        const res = await this.$server[url]({
            data: {
                // 这里的id是上报的数据id
                id: this._isCopy ? "" : this.$route.query.rowId,
                // 传过来的id是formId
                formId: this._isCopy ? "" : this.$route.query.id,
                receiverId: this.model.receiverId,
                categoryId: Array.isArray(this.model.categoryId) ? this.model.categoryId[1] : this.model.categoryId,
                formDto: {
                    ...params,
                    formKind: 5,
                    status: params.status,
                    id: this._isCopy ? "" : this.$route.query.id
                },
                status: params.status
            }
        });
        if (res.data.code === 200) {
            this.$message.success("操作成功");
            this.resetInterceptRouter(() => {
                this.$router.push({
                    name: "DeclareConfig"
                });
            });
        } else {
            this.$message.error(res.data.message);
        }
    }

    // 绑定流程
    bindFlow(id: any, type?: any) {
        this.$server["process/processBind"]({
            data: {
                formId: this.$route.query.id || this.nowId,
                processId: id
            }
        })
            .then((res: any) => {
                if (res.data.code === 200) {
                    this.$message.success("操作成功");
                    this.updateStatus(id, type);
                } else {
                    this.$message.error(res.data.message);
                }
            })
            .catch();
    }

    // 修改表单状态
    updateStatus(id: any, type?: any) {
        this.$server["moduleManage/updateStatus"]({
            params: {
                formId: this.$route.query.id || this.nowId,
                status: 1
            }
        }).then((r: any) => {
            if (r.data.code === 200) {
                if (type === "SENDTASK") {
                    this.$router.push({
                        name: "TownModuleManageForm",
                        query: {
                            id: this.$route.query.id || this.nowId,
                            processId: id,
                            isSend: "send"
                        }
                    });
                    this.getFormItem();
                    this.$store.dispatch("updateSelectedControl", {});
                } else {
                    this.goBackList();
                }
            } else {
                this.$message.error("修改流程状态失败");
            }
        });
    }

    getFormItem() {
        // console.log(this.jsonCustom);
    }

    // 预览
    showPreview() {
        if (this.childTab === 'rich') {
            this.wechatDialogVisible = true;
        } else {
            this.showPreviewDialog = true;
        }
    }

    // 修改预览类型
    changePreview() {
        this.previewType = this.previewType === "form" ? "table" : "form";
    }
}
